using MediatR;
using Medical.Domain;
using Medical.Infrastructrue.Interfaces;
using Medical.ReadApi.Dto;
using Medical.WriteApi.Appcontext.Command;
using Medical.WriteApi.Dto;

namespace Medical.WriteApi.Appcontext.CommandHandler
{
	public class UpdateDepartmentCommandHandler : IRequestHandler<UpdateDepartmentCommand, DepartmentDto>
	{
		private readonly IBaseRepository<Department> _repository;

		public UpdateDepartmentCommandHandler(IBaseRepository<Department> repository)
		{
			_repository = repository;
		}

		public async Task<DepartmentDto> Handle(UpdateDepartmentCommand request, CancellationToken cancellationToken)
		{
			var entity = await _repository.GetModel(x => x.DepartmentId == request.DepartmentId && !x.IsDeleted);
			if (entity == null) throw new Exception("科室不存在");

			if (!string.IsNullOrEmpty(request.Name)) entity.Name = request.Name;
			if (request.Address != null) entity.Address = request.Address;
			if (request.RegistrationFee.HasValue) entity.RegistrationFee = request.RegistrationFee.Value;
			if (request.ParentDepartmentId.HasValue) entity.ParentDepartmentId = request.ParentDepartmentId;
			if (request.IsKeyDepartment.HasValue) entity.IsKeyDepartment = request.IsKeyDepartment.Value;
			if (request.IsEmergencyAvailable.HasValue) entity.IsEmergencyAvailable = request.IsEmergencyAvailable.Value;
			if (request.BedCount.HasValue) entity.BedCount = request.BedCount.Value;

			entity.UpdatedAt = DateTime.Now;
			await _repository.UpdateAsync(entity);

			return new DepartmentDto
			{
				DepartmentId = entity.DepartmentId,
				Name = entity.Name,
				Address = entity.Address,
				RegistrationFee = entity.RegistrationFee,
				ParentDepartmentId = entity.ParentDepartmentId,
				IsKeyDepartment = entity.IsKeyDepartment,
				IsEmergencyAvailable = entity.IsEmergencyAvailable,
				BedCount = entity.BedCount,
				CreatedAt = entity.CreatedAt,
				UpdatedAt = entity.UpdatedAt
			};
		}
	}
}
